package com.cande.loki.exercise.algorithm;

import java.util.HashMap;

/**
 * 两数之和 给一个数 从数组中找到两个数加起来等于它
 */
public class TwoNumberSum {
    public static void main(String[] args) throws Exception {
        int [] arr = twoSum(new int[]{1,2,4} , 6);
        System.out.println( arr[0] + ": " + arr[1]);
    }
    public static int[] twoSum(int[] nums, int target) throws Exception {
        int[] result = new int[2];
        HashMap<Integer ,Integer> hashMap = new HashMap();

        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (hashMap.containsKey(diff)){
                result[0] = i; result[1] = hashMap.get(diff);
                return  result;
            }
            hashMap.put(nums[i], i);
        }
        throw new Exception("no result");
    }
}
